package com.hbwxz;

import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.client.indices.GetIndexResponse;

import java.io.IOException;

/**
 * 记得测试的时候启动 ElasticSearch 和 Kibana
 *
 * @author shenzw
 * @date 2024/1/21
 */
public class EsLearning {
    public static void main(String[] args) throws IOException {

        RestHighLevelClient restHighLevelClient = new RestHighLevelClient(
                RestClient.builder(new HttpHost("127.0.0.1", 9200))
        );

        try {
//            testConnection(restHighLevelClient); // 测试连通性

//            createIndex(restHighLevelClient); // 创建 index

//            getIndex(restHighLevelClient); // 获取 index

//            deleteIndex(restHighLevelClient); // 删除 index

        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            restHighLevelClient.close();
        }


    }

    /**
     * 删除 index
     */
    private static void deleteIndex(RestHighLevelClient restHighLevelClient) throws IOException {

        DeleteIndexRequest test = new DeleteIndexRequest("test");
        AcknowledgedResponse delete = restHighLevelClient.indices().delete(test, RequestOptions.DEFAULT);
        System.out.println(delete.isAcknowledged());

    }

    /**
     * 获取 index
     */
    private static void getIndex(RestHighLevelClient restHighLevelClient) throws IOException {
        GetIndexRequest getIndexRequest = new GetIndexRequest("test");
        GetIndexResponse getIndexResponse = restHighLevelClient.indices().get(getIndexRequest, RequestOptions.DEFAULT);
        System.out.println(getIndexResponse.getIndices()); // [Ljava.lang.String;@41005828
    }

    /**
     * 创建 index，观察打印信息为 true
     */
    private static void createIndex(RestHighLevelClient restHighLevelClient) throws IOException {
        CreateIndexRequest test = new CreateIndexRequest("test");
        CreateIndexResponse createIndexResponse = restHighLevelClient.indices().create(test, RequestOptions.DEFAULT);
        System.out.println(createIndexResponse.isAcknowledged()); // true
    }

    /**
     * 测试连通性
     */
    private static void testConnection(RestHighLevelClient restHighLevelClient) throws IOException {
        // RestHighLevelClient 一直是比较流行的，很多项目是在他 deprecated 之前写的
        // 测试连通性，只要没报错就 ok
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(new HttpHost("127.0.0.1", 9200))
        );

        client.close();
    }
}